//! 服务管理器 - 统一管理所有服务组件
//! 
//! 基于单一职责原则设计的服务管理器，负责：
//! 1. 服务生命周期管理
//! 2. 组件协调
//! 3. 资源管理

use crate::server::enhanced_traits::*;
use async_trait::async_trait;
use std::io;
use std::sync::Arc;
use tokio::sync::RwLock;
use tracing::{info, error, warn};

/// 服务管理器 - 实现单一职责原则
/// 
/// 职责：
/// - 管理多个服务组件的生命周期
/// - 协调服务间的依赖关系
/// - 提供统一的服务管理接口
pub struct ServiceManager {
    /// 管理的服务组件列表
    services: Vec<Box<dyn ServiceLifecycle>>,
    
    /// 服务状态
    is_running: bool,
    
    /// 事件发布器
    event_publisher: Arc<dyn ServerEventPublisher>,
    
    /// 配置
    config: Box<dyn ServerConfig>,
}

impl ServiceManager {
    /// 创建新的服务管理器
    pub fn new(
        config: Box<dyn ServerConfig>,
        event_publisher: Arc<dyn ServerEventPublisher>,
    ) -> Self {
        Self {
            services: Vec::new(),
            is_running: false,
            event_publisher,
            config,
        }
    }
    
    /// 添加服务组件
    pub fn add_service(&mut self, service: Box<dyn ServiceLifecycle>) {
        info!("添加服务组件: {}", service.service_name());
        self.services.push(service);
    }
    
    /// 移除服务组件
    pub fn remove_service(&mut self, service_name: &str) -> Option<Box<dyn ServiceLifecycle>> {
        if let Some(index) = self.services.iter().position(|s| s.service_name() == service_name) {
            info!("移除服务组件: {}", service_name);
            Some(self.services.remove(index))
        } else {
            warn!("未找到服务组件: {}", service_name);
            None
        }
    }
    
    /// 获取服务组件数量
    pub fn service_count(&self) -> usize {
        self.services.len()
    }
    
    /// 获取所有服务名称
    pub fn service_names(&self) -> Vec<&str> {
        self.services.iter().map(|s| s.service_name()).collect()
    }
}

#[async_trait]
impl ServiceLifecycle for ServiceManager {
    fn service_name(&self) -> &'static str {
        "ServiceManager"
    }
    
    /// 启动所有管理的服务
    async fn start(&mut self) -> io::Result<()> {
        if self.is_running {
            warn!("ServiceManager已经在运行中");
            return Ok(());
        }
        
        info!("🚀 启动ServiceManager，管理{}个服务", self.services.len());
        
        // 发布启动事件
        let mode = self.config.mode();
        if let Err(e) = self.event_publisher.publish(ServerEvent::Starting { mode }).await {
            error!("发布启动事件失败: {}", e);
        }
        
        // 按顺序启动所有服务
        let service_count = self.services.len();
        for (index, service) in self.services.iter_mut().enumerate() {
            info!("启动服务 {}/{}: {}", index + 1, service_count, service.service_name());
            
            if let Err(e) = service.start().await {
                error!("启动服务失败: {} - {}", service.service_name(), e);
                
                // 发布错误事件
                if let Err(event_err) = self.event_publisher.publish(
                    ServerEvent::Error { 
                        message: format!("服务启动失败: {} - {}", service.service_name(), e),
                        recoverable: false 
                    }
                ).await {
                    error!("发布错误事件失败: {}", event_err);
                }
                
                // 启动失败时，停止已启动的服务
                self.stop_started_services(index).await;
                return Err(e);
            }
            
            info!("✅ 服务启动成功: {}", service.service_name());
        }
        
        self.is_running = true;
        
        // 发布启动完成事件
        let mode = self.config.mode(); // 重新获取，避免移动问题
        let bind_addr = self.config.bind_address().to_string();
        if let Err(e) = self.event_publisher.publish(
            ServerEvent::Started { mode, bind_addr }
        ).await {
            error!("发布启动完成事件失败: {}", e);
        }
        
        info!("✅ ServiceManager启动成功，所有服务已就绪");
        Ok(())
    }
    
    /// 停止所有管理的服务
    async fn stop(&mut self) -> io::Result<()> {
        if !self.is_running {
            warn!("ServiceManager未在运行中");
            return Ok(());
        }
        
        info!("🛑 停止ServiceManager，管理{}个服务", self.services.len());
        
        // 发布停止事件
        let mode = self.config.mode();
        if let Err(e) = self.event_publisher.publish(ServerEvent::Stopping { mode }).await {
            error!("发布停止事件失败: {}", e);
        }
        
        // 按逆序停止所有服务（后启动的先停止）
        self.stop_all_services().await;
        
        self.is_running = false;
        
        // 发布停止完成事件
        if let Err(e) = self.event_publisher.publish(ServerEvent::Stopped { mode }).await {
            error!("发布停止完成事件失败: {}", e);
        }
        
        info!("✅ ServiceManager已停止");
        Ok(())
    }
    
    fn is_running(&self) -> bool {
        self.is_running
    }
    
    /// 优雅关闭所有服务
    async fn graceful_shutdown(&mut self, timeout_secs: u64) -> io::Result<()> {
        if !self.is_running {
            return Ok(());
        }
        
        info!("🔄 开始优雅关闭ServiceManager（超时: {}秒）", timeout_secs);
        
        // 创建超时任务
        let timeout_duration = std::time::Duration::from_secs(timeout_secs);
        let shutdown_task = async {
            // 尝试优雅关闭每个服务
            let service_count = self.services.len();
            for service in self.services.iter_mut().rev() {
                info!("优雅关闭服务: {}", service.service_name());
                if let Err(e) = service.graceful_shutdown(timeout_secs / service_count as u64).await {
                    warn!("服务优雅关闭失败，强制停止: {} - {}", service.service_name(), e);
                    if let Err(stop_err) = service.stop().await {
                        error!("强制停止服务失败: {} - {}", service.service_name(), stop_err);
                    }
                }
            }
            self.is_running = false;
        };
        
        // 执行带超时的优雅关闭
        if let Err(_) = tokio::time::timeout(timeout_duration, shutdown_task).await {
            warn!("优雅关闭超时，执行强制停止");
            self.stop().await?;
        }
        
        info!("✅ ServiceManager优雅关闭完成");
        Ok(())
    }
}

impl ServiceManager {
    /// 停止已启动的服务（用于启动失败时的清理）
    async fn stop_started_services(&mut self, up_to_index: usize) {
        info!("清理已启动的服务（0到{}）", up_to_index);
        
        for i in (0..up_to_index).rev() {
            if let Some(service) = self.services.get_mut(i) {
                info!("停止服务: {}", service.service_name());
                if let Err(e) = service.stop().await {
                    error!("停止服务失败: {} - {}", service.service_name(), e);
                }
            }
        }
    }
    
    /// 停止所有服务
    async fn stop_all_services(&mut self) {
        let service_count = self.services.len();
        for (index, service) in self.services.iter_mut().rev().enumerate() {
            info!("停止服务 {}/{}: {}", index + 1, service_count, service.service_name());
            if let Err(e) = service.stop().await {
                error!("停止服务失败: {} - {}", service.service_name(), e);
            } else {
                info!("✅ 服务停止成功: {}", service.service_name());
            }
        }
    }
}

#[async_trait]
impl HealthCheck for ServiceManager {
    /// 检查所有服务的健康状态
    async fn health_check(&self) -> Result<HealthStatus, String> {
        if !self.is_running {
            return Ok(HealthStatus::Unhealthy("ServiceManager未运行".to_string()));
        }
        
        let mut _healthy_count = 0;
        let degraded_count = 0;
        let mut unhealthy_count = 0;
        let mut error_messages = Vec::new();
        
        for service in &self.services {
            // 基本健康检查 - 检查服务是否运行
            if service.is_running() {
                _healthy_count += 1;
            } else {
                unhealthy_count += 1;
                error_messages.push(format!("服务未运行: {}", service.service_name()));
            }
            
            // 如果服务实现了HealthCheck trait，执行详细检查
            // 注意：由于类型系统限制，这里暂时跳过健康检查
            // TODO: 重新设计trait层次结构以支持运行时类型检查
        }
        
        // 根据结果确定整体健康状态
        if unhealthy_count > 0 {
            Ok(HealthStatus::Unhealthy(error_messages.join("; ")))
        } else if degraded_count > 0 {
            Ok(HealthStatus::Degraded(error_messages.join("; ")))
        } else {
            Ok(HealthStatus::Healthy)
        }
    }
    
    /// 获取所有服务的诊断信息
    async fn diagnostics(&self) -> Vec<DiagnosticInfo> {
        let mut diagnostics = Vec::new();
        
        // ServiceManager自身的诊断信息
        diagnostics.push(DiagnosticInfo {
            component: "ServiceManager".to_string(),
            status: if self.is_running { "Running" } else { "Stopped" }.to_string(),
            details: Some(format!("管理{}个服务", self.services.len())),
        });
        
        // 各服务的诊断信息
        for service in &self.services {
            diagnostics.push(DiagnosticInfo {
                component: service.service_name().to_string(),
                status: if service.is_running() { "Running" } else { "Stopped" }.to_string(),
                details: None,
            });
            
            // 如果服务实现了HealthCheck trait，获取详细诊断信息
            // 注意：由于类型系统限制，这里暂时跳过诊断信息
            // TODO: 重新设计trait层次结构以支持运行时类型检查
        }
        
        diagnostics
    }
}

/// 并发安全的服务管理器
/// 
/// 提供线程安全的服务管理功能，支持并发访问
pub struct ConcurrentServiceManager {
    inner: Arc<RwLock<ServiceManager>>,
}

impl ConcurrentServiceManager {
    /// 创建新的并发服务管理器
    pub fn new(
        config: Box<dyn ServerConfig>,
        event_publisher: Arc<dyn ServerEventPublisher>,
    ) -> Self {
        Self {
            inner: Arc::new(RwLock::new(ServiceManager::new(config, event_publisher))),
        }
    }
    
    /// 添加服务（异步安全）
    pub async fn add_service(&self, service: Box<dyn ServiceLifecycle>) {
        let mut manager = self.inner.write().await;
        manager.add_service(service);
    }
    
    /// 移除服务（异步安全）
    pub async fn remove_service(&self, service_name: &str) -> Option<Box<dyn ServiceLifecycle>> {
        let mut manager = self.inner.write().await;
        manager.remove_service(service_name)
    }
    
    /// 获取服务数量
    pub async fn service_count(&self) -> usize {
        let manager = self.inner.read().await;
        manager.service_count()
    }
    
    /// 获取健康状态
    pub async fn health_check(&self) -> Result<HealthStatus, String> {
        let manager = self.inner.read().await;
        manager.health_check().await
    }
}

#[async_trait]
impl ServiceLifecycle for ConcurrentServiceManager {
    fn service_name(&self) -> &'static str {
        "ConcurrentServiceManager"
    }
    
    async fn start(&mut self) -> io::Result<()> {
        let mut manager = self.inner.write().await;
        manager.start().await
    }
    
    async fn stop(&mut self) -> io::Result<()> {
        let mut manager = self.inner.write().await;
        manager.stop().await
    }
    
    fn is_running(&self) -> bool {
        // 注意：这里可能存在竞态条件，但对于状态查询来说是可接受的
        // 如果需要强一致性，可以改为异步方法
        if let Ok(manager) = self.inner.try_read() {
            manager.is_running()
        } else {
            false // 锁争用时返回保守结果
        }
    }
    
    async fn graceful_shutdown(&mut self, timeout_secs: u64) -> io::Result<()> {
        let mut manager = self.inner.write().await;
        manager.graceful_shutdown(timeout_secs).await
    }
}